<template>
  <div class="login-container">
    <!-- 登录标题 -->
    <div class="login-title">
      <h1>欢迎回来！</h1>
      <div class="subtitle">Please login to your accounts</div>
    </div>

    <!-- 登录表单，使用两种登录方式：账号密码登录，手机号验证码登录 -->
    <div class="login-form">
      <van-form>
        <!-- 账号登录 -->
        <van-field v-model="account" name="账号" label="账号" placeholder="请输入账号" v-if="loginMode === 'account'" />
        <van-field v-model="password" :type="text" name="密码" label="密码" placeholder="密码(6-16位)" :right-icon="eye" @click-right-icon="toggleEye" v-if="loginMode === 'account'" maxlength="16" />

        <!-- 手机号登录 -->
        <van-field v-model="phone" label="手机号" placeholder="请输入手机号" maxlength="11" v-if="loginMode === 'phone'">
          <template #button>
            <van-button size="small" type="primary" color="#0C34BA" @click="getEmailValidatorCode" v-if="flag">发送验证码</van-button>
            <van-button size="small" type="primary" color="#0C34BA" disabled v-else>{{ timeCount }}s后重新发送</van-button>
          </template>
        </van-field>

        <van-field label="验证码" v-model="code" placeholder="验证码(6位数字)" maxlength="6" v-if="loginMode === 'phone'" />

        <div class="forget-pwd" v-show="loginMode === 'account'">
          <span @click="forget">忘记密码？</span>
        </div>
        <div class="login-btn">
          <van-button round block type="info" @click="onSubmit">登录</van-button>
        </div>
      </van-form>

      <!-- 注册按钮以及弹出框 -->
      <div class="login-btn">
        <van-button class="register-btn" round block @click="show = true">注册</van-button>
        <van-button class="register-btn" round block @click="toggleLoginMode">{{ loginText }}</van-button>
        <van-popup v-model="show" position="bottom" closeable :style="{ 'min-height': '44.5%' }">
          <register-com @toggle-show="(val) => (show = val)" @hideRegisterForm="show = false"></register-com>
        </van-popup>
      </div>
    </div>
  </div>
</template>

<script>
import RegisterCom from '@/components/login/RegisterViewCom.vue'
import axios from '@/utils/request/request'
import { Notify } from 'vant'

export default {
  name: 'login',
  data() {
    return {
      account: '',
      password: '',
      eye: 'closed-eye',
      text: 'password',
      show: false,
      loginText: '手机号登录',
      loginMode: 'account',
      codePattern: /^\d{6}$/,
      code: '',
      flag: true,
      timer: null,
      timeCount: 60,
      phone: ''
    }
  },
  components: {
    RegisterCom
  },
  methods: {
    async onSubmit() {
      if (this.loginMode === 'phone') {
        // 手机号不能为空并且格式不能错误
        if (this.phone == '') {
          return Notify({
            type: 'danger',
            message: '请输入手机号！'
          })
        }
        if (!/^1[3-9]\d{9}$/.test(this.phone)) {
          return Notify({
            type: 'danger',
            message: '手机号格式错误！'
          })
        }

        // 验证验证码是否正确
        if (this.code === '') {
          return Notify({
            type: 'danger',
            message: '请输入验证码！',
            duration: 1000
          })
        }
        if (!this.codePattern.test(this.code)) {
          return Notify({
            type: 'danger',
            message: '验证码为6位有效数字！',
            duration: 1000
          })
        }

        this.$toast.loading({
          duration: 0,
          message: '加载中...',
          loadingType: 'spinner'
        })
        try {
          const data = await axios.post('/api/user/login', { phone: this.phone, code: this.code })
          if (data.code === 0) {
            Notify({
              type: 'success',
              message: data.msg
            })
            // 将用户token保存到本地
            localStorage.setItem('user_token', data.token)
            this.$router.replace('/home')
          } else {
            Notify({
              type: 'danger',
              message: data.msg
            })
          }
        } catch {
          Notify({
            type: 'danger',
            message: '请求失败！',
            duration: 1000
          })
        } finally {
          this.$toast.clear()
        }
      } else {
        // 账号不能为空长度位1-64
        if (this.account === '')
          return Notify({
            type: 'danger',
            message: '请输入账号！',
            duration: 1000
          })
        if (this.account.length > 64)
          return Notify({
            type: 'danger',
            message: '账号长度为1-64位！',
            duration: 1000
          })

        // 密码验证
        if (this.password === '')
          return Notify({
            type: 'danger',
            message: '请输入密码！',
            duration: 1000
          })
        if (!/^(?=.*[a-zA-Z])(?=.*[0-9])[A-Za-z0-9]{6,16}$/.test(this.password))
          return Notify({
            type: 'danger',
            message: '密码必须为6-16的数字字母组合！',
            duration: 1000
          })

        // 发起请求登录
        this.$toast.loading({
          duration: 0,
          message: '加载中...',
          loadingType: 'spinner'
        })
        try {
          const data = await axios.post('/api/user/login', { account: this.account, password: this.password })
          if (data.code === 0) {
            Notify({
              type: 'success',
              message: data.msg
            })
            // 将用户token保存到本地
            localStorage.setItem('user_token', data.token)
            this.$router.replace('/home')
          } else {
            Notify({
              type: 'danger',
              message: data.msg
            })
          }
        } catch {
          Notify({
            type: 'danger',
            message: '请求失败！',
            duration: 1000
          })
        } finally {
          this.$toast.clear()
        }
      }
    },
    // 切换密码输入框的type类型
    toggleEye() {
      if (this.eye === 'closed-eye') {
        this.eye = 'eye-o'
        this.text = 'text'
      } else {
        this.eye = 'closed-eye'
        this.text = 'password'
      }
    },
    // 忘记密码
    forget() {
      this.$router.push('/forget')
    },
    // 切换登录方式
    toggleLoginMode() {
      if (this.loginMode === 'account') {
        this.loginMode = 'phone'
        this.loginText = '账号登录'
      } else {
        this.loginMode = 'account'
        this.loginText = '手机号登录'
      }
    },
    // 发送验证码
    async getEmailValidatorCode() {
      // 手机号不能为空并且格式不能错误
      if (this.phone == '') {
        return Notify({
          type: 'danger',
          message: '请输入手机号！'
        })
      }
      if (!/^1[3-9]\d{9}$/.test(this.phone)) {
        return Notify({
          type: 'danger',
          message: '手机号格式错误！',
          duration: 1000
        })
      }
      this.$toast.loading({
        duration: 0,
        message: '加载中...',
        loadingType: 'spinner'
      })
      try {
        // 发起请求获取验证码
        const data = await axios.post('/api/getcode', {
          phone: this.phone
        })
        // 获取成功
        if (data.code === 0) {
          this.flag = false
          Notify({
            type: 'success',
            message: '验证码发送成功，请注意查收！',
            duration: 1000
          })
          this.timer = setInterval(() => {
            this.timeCount--
            if (this.timeCount <= 0) {
              clearInterval(this.timer)
              this.timeCount = 60
              this.flag = true
            }
          }, 1000)
        } else {
          Notify({
            type: 'danger',
            message: data.msg,
            duration: 1000
          })
        }
      } catch {
        Notify({
          type: 'danger',
          message: '请求失败！',
          duration: 1000
        })
      } finally {
        this.$toast.clear()
      }
    }
  }
}
</script>

<style lang="less" scoped>
.login-container {
  .login-title {
    padding: 120px 10px 0;
    h1 {
      font-size: 24px;
      font-weight: 700;
    }
    .subtitle {
      margin-top: 15px;
      color: #999;
      font-size: 18px;
    }
  }
  .login-form {
    margin-top: 40px;
    padding: 0 10px;

    .forget-pwd {
      height: 20px;
      margin-top: 20px;
      text-align: right;

      span {
        color: #666;
        font-size: 14px;
      }
    }

    ::v-deep .van-field__label {
      width: 4em;
    }
    ::v-deep .van-field--error .van-field__control,
    ::v-deep .van-field--error .van-field__control::placeholder {
      color: rgba(50, 50, 50, 0.5);
      -webkit-text-fill-color: currentColor;
    }

    .login-btn {
      margin-top: 20px;

      .van-button--info {
        background-color: #f92946;
        border-color: #f92946;
      }

      .register-btn {
        background-color: #fff;
        color: rgb(50, 50, 51);
        border: 1px solid rgb(235, 237, 240);
        margin-bottom: 20px;
      }
    }
  }
}
</style>
